#import "TSSpilteTableView.h"
#import "TSMsgContentItemCell.h"
#import "TSMsgDatePickerTextFieldCell.h"
#import "TSPickerViewTextFieldCell.h"
#import "FBFilesTableViewController.h"
@implementation TSSpilteTableView{
    NSArray *rowsArray;
    BOOL isManualScroll;
    CGPoint point;
    NSMutableDictionary *cellDic;
    TSTaskModel * taskModel;
    NSMutableArray<TSTaskModel>* taskArray;
}

@synthesize nodeCount,userArray;

- (id)initWithFrame:(CGRect)frame
{
    nodeCount = 1;
    if (self=[super initWithFrame:frame]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMultipleSelectCompelete:) name:TSNotification_OnMultipleSelectCompelete object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveContentViewController:) name:TSNotification_SaveContentController object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShown:) name:UIKeyboardDidShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHidden:) name:UIKeyboardDidHideNotification object:nil];
        
        
        rowsArray = @[@"标题:", @"内容:",@"开始时间:",@"结束时间:", @"办事人:"];
        
        self.dataSource = self;
        self.delegate = self;
        self.scrollEnabled=YES;
        self.tableFooterView = [[UIView alloc] init];
        
        userArray = [[NSMutableArray alloc] initWithCapacity:10];
        cellDic = [[NSMutableDictionary alloc] initWithCapacity:10];
        taskArray = [[NSMutableArray alloc] initWithCapacity:10];
    }
    
    return self;
}

-(void)initData:(TSTaskModel *)task{
    taskModel = task;
    if([TSTools isEmpty:taskModel.temNext])return;
    NSData * data = [taskModel.temNext dataUsingEncoding:NSASCIIStringEncoding];
    NSArray * ta = [self toArrayOrNSDictionary:data];
    for(NSDictionary * dic in ta){
       TSTaskModel *ts =  [[TSTaskModel alloc] initWithJSONDict: dic];
        [taskArray addObject:ts];
        [userArray addObject:@(ts.receiveId)];
    }
    if([taskArray count]==0){
     [userArray addObject:@""];
    }
    nodeCount = [taskArray count]>0?[taskArray count]:1;
    [self reloadData];
}

- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
    
}

-(void)saveContentViewController:(NSNotification *)noti
{
    NSIndexPath *path = [NSIndexPath indexPathForRow:1 inSection:[[noti.userInfo objectForKey:@"section"] intValue]];
    TSMsgContentItemCell *cell = (TSMsgContentItemCell *)[self cellForRowAtIndexPath:path];
    [cell.contentTextField setText:noti.object];
}

- (void)onMultipleSelectCompelete:(NSNotification *)noti
{
    NSArray * names = [noti.object objectForKey:TSDictionaryKeyDefine_Name];
    NSNumber *type  = (NSNumber *)[noti.object objectForKey:TSDictionaryKeyDefine_Type];
    NSInteger section = [[noti.object objectForKey:@"section"] intValue];
    NSIndexPath *path;
    if (type.integerValue == ToolBarTextField_Type_Receive) {
        path = [NSIndexPath indexPathForRow:4 inSection:section];
    }
    else if (type.integerValue == ToolBarTextField_Type_Audit){
        path = [NSIndexPath indexPathForRow:6 inSection:section];
    }
    else if (type.integerValue == ToolBarTextField_Type_Supervise){
        path = [NSIndexPath indexPathForRow:5 inSection:section];
    }
    
    TSMsgContentItemCell *cell = (TSMsgContentItemCell *)[self cellForRowAtIndexPath:path];
    [userArray replaceObjectAtIndex:path.section withObject:[self getIds:names]];
    [cell.contentTextField setText:[self getNames:names]];
    
    //    if (type.integerValue == ToolBarTextField_Type_Receive) {
    //        taskModel.auditId = [self getNames:names];
    //    }
    //    else if (type.integerValue == ToolBarTextField_Type_Audit){
    //        taskModel.auditId = [self getNames:names];
    //    }
}

//指定有多少个分区(Section)，默认为1

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return nodeCount;//返回标题数组中元素的个数来确定分区的个数
    
}

- (NSString *)getNames:(NSArray *)names
{
    NSMutableString *name_str = [[NSMutableString alloc] initWithString:@""];
    if (names && names.count > 0) {
        
        for (int i=0; i<names.count; i++) {
            TSUserModel *model = [names objectAtIndex:i];
            [name_str appendString:model.userName];
            
            if (i < names.count-1) {
                [name_str appendString:@","];
            }
        }
    }
    
    return name_str;
}

- (NSString *)getIds:(NSArray *)names
{
    NSMutableString *name_str = [[NSMutableString alloc] initWithString:@""];
    if (names && names.count > 0) {
        
        for (int i=0; i<names.count; i++) {
            TSUserModel *model = [names objectAtIndex:i];
            [name_str appendString:model.userId];
            
            if (i < names.count-1) {
                [name_str appendString:@","];
            }
        }
    }
    
    return name_str;
}

/* 是否属于picker cell */
- (CELL_TYTPE)getCellType:(NSString *)name
{
    NSArray *date_picker_array = @[@"开始时间:",@"结束时间:"];
    
    for (NSString *picker_name in date_picker_array) {
        if ([picker_name isEqualToString:name]) {
            return DATE_PICKER_TEXT_FIELD_CELL;
        }
    }
    
    return DEFAULT_TEXT_FIELD_CELL;
}
//每个section显示的标题

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    return [NSString stringWithFormat:@"%@%d",@"节点",section+1];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return rowsArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *title = [rowsArray objectAtIndex:indexPath.row];
    if([title isEqualToString:@"内容:"]){
        return 200;
    }else{
        return CELL_HEIGHT;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    NSString *title = [rowsArray objectAtIndex:indexPath.row];
    CELL_TYTPE cell_type = [self getCellType:title];
    
    NSMutableDictionary *cellArr = [cellDic objectForKey:title];
    
    if(!cellArr){
        cellArr = [[NSMutableDictionary alloc] initWithCapacity:10];
        [cellDic setObject:cellArr forKey:title];
    }
    TSTaskModel * model = nil;
    if(taskArray&&[taskArray count]>indexPath.section){
      model = [taskArray objectAtIndex:indexPath.section];
    }
    if (rowsArray && rowsArray.count > indexPath.row) {
        switch (cell_type) {
            case DEFAULT_TEXT_FIELD_CELL:
            {
                NSString *item_cell_identi  = [NSString stringWithFormat:@"%@%@%@",@"item_cell_identi",@(indexPath.section),@(indexPath.row)];
                TSMsgContentItemCell *item_cell = [tableView dequeueReusableCellWithIdentifier:item_cell_identi];
                if(!item_cell){
                    item_cell = [[TSMsgContentItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:item_cell_identi];
                }
                [item_cell setTitleAndTextField:title Type:UITextFieldDefault];
                
                if ([title isEqualToString:@"办事人:"]){
                    [item_cell setToolBarTextFieldType:ToolBarTextField_Type_Receive];
                    [item_cell setNotShowKeyboard:YES];
                    if(model){
                        [item_cell.contentTextField setText:model.receiveName];
                    }
                }
                else if ([title isEqualToString:@"内容:"]){
                    [item_cell setToolBarTextFieldType:ToolBarTextField_Type_Content];
                    [item_cell setNotShowKeyboard:YES];
                    if(model){
                        [item_cell.contentTextField setText:model.content];
                    }
                    CGRect frame = item_cell.contentTextField.frame;
                    frame.size.height =180;
                    item_cell.contentTextField.frame = frame;
                }else if([title isEqualToString:@"标题:"]){
                    if(model){
                        [item_cell.contentTextField setText:model.title];
                    }
                }
                [item_cell setTextFieldSection:indexPath.section];
                cell =item_cell;
                item_cell.contentTextField.delegate = self;
            }
                break;
            case DATE_PICKER_TEXT_FIELD_CELL:
            {
                 NSString *picker_cell_identi  = [NSString stringWithFormat:@"%@%@%@",@"picker_cell",@(indexPath.section),@(indexPath.row)];
                TSMsgDatePickerTextFieldCell *picker_cell = [tableView dequeueReusableCellWithIdentifier:picker_cell_identi];
                    picker_cell = [[TSMsgDatePickerTextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:picker_cell_identi];
                    [picker_cell setTitle:title];
                if([title isEqualToString:@"开始时间:"]){
                    if(model){
                        [picker_cell.contentTextField setText:[TSTools getDateByTime:model.timeBegin]];

                    }
                }else if([title isEqualToString:@"结束时间:"]){
                    if(model){
                        [picker_cell.contentTextField setText:[TSTools getDateByTime:model.timeEnd]];
                    }
                }
                cell = picker_cell;
            }
                break;
            default:
                break;
        }
    }
    
    [cellArr setObject:cell forKey:@(indexPath.section)];
    return cell;
}

-(void)selectFile
{
    NSArray *docs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    FBFilesTableViewController * ftView = [[FBFilesTableViewController alloc] initWithPath:docs[0]];
    ftView.vc_root = [self getViewController];
    [self.getViewController.navigationController pushViewController:ftView animated:YES];
}

- (UITableViewCell *)getCellByTitle:(NSString *)title section:(NSInteger)section
{
    return [[cellDic objectForKey:title] objectForKey:@(section)];
}

- (NSIndexPath *)getIndexPathByTitle:(NSString *)title section:(NSInteger)section
{
    if (rowsArray) {
        for (int i=0; i<rowsArray.count; i++) {
            if ([[rowsArray objectAtIndex:i] isEqualToString:title]) {
                NSIndexPath *index_path = [NSIndexPath indexPathForItem:i inSection:section];
                return index_path;
            }
        }
    }
    
    return nil;
}

- (NSString *)getTextByTitle:(NSString *)title
{
    NSString *result_text = @"";
    if (taskModel) {
        if ([title isEqualToString:@"标题:"]) {
            result_text = taskModel.title;
        }
        else if ([title isEqualToString:@"开始时间:"]) {
            result_text = [TSTools getDateByTime:taskModel.timeBegin];
        }
        else if ([title isEqualToString:@"结束时间:"]) {
            result_text = [TSTools getDateByTime:taskModel.timeEnd];
        }
        else if ([title isEqualToString:@"内容:"]) {
            result_text = taskModel.content;
        }
        else if ([title isEqualToString:@"办事人:"]) {
            result_text = taskModel.receiveName;
        }
    
    }
    return result_text;
}

-(void) keyboardShown:(NSNotification*) notification {
    //isManualScroll= YES;
    // [self setContentOffset:CGPointMake(0.0, 300) animated:YES];
}

-(void) keyboardHidden:(NSNotification*) notification {
    // [self setContentOffset:CGPointMake(0.0, 0) animated:YES];
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    //    CGFloat y = textView.frame.origin.x;
    //    CGFloat offset = y-currentDeviceHeight+NAV_AND_STATUS_BAR_HEIGHT+316;
    //    if(offset>0){
    //        [self setContentOffset:CGPointMake(0.0, offset) animated:YES];
    //    }
    
    
    UITableViewCell * cell=(UITableViewCell *)[textView  superview];
    NSIndexPath *indexPath=[self indexPathForCell:cell];
    CGFloat heightFormTop = [self getCellHeightFromTop:indexPath.row];
    CGFloat offset = heightFormTop-currentDeviceHeight+NAV_AND_STATUS_BAR_HEIGHT+316;
    if(offset>0){
        [self setContentOffset:CGPointMake(0.0, offset) animated:YES];
    }
    
}
- (void)textViewDidEndEditing:(UITextView *)textView{
    [self setContentOffset:CGPointMake(0.0, 0) animated:YES];
}

-(CGFloat)getCellHeightFromTop:(NSInteger) row
{
    if(row>3){
        return 200+CELL_HEIGHT*row;
    }else{
        return CELL_HEIGHT*(row+1);
    }
}

- (void)saveViewController:(NSNotification *)noti
{
    NSInteger section =[[noti.userInfo objectForKey:@"section"] intValue];
    NSString *editContent = noti.object;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:section];
    TSMsgContentItemCell *cell = (TSMsgContentItemCell *)[self cellForRowAtIndexPath:indexPath];
    [cell.contentTextField setText:editContent];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


//-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSIndexPath *path =  [self indexPathForRowAtPoint:CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y)];
//    //保存当前内容
//    [self saveTextByTitle:path];
//}


- (NSString *)getContentByTitle:(NSString *)title section:(NSInteger)section
{
    //    @[@"标题:", @"时间:", @"地点:", @"内容:", @"发送人:", @"接收人:", @"审核人:", @"附件:", @"时限:"];
    NSString *content = @"";
    UITableViewCell *cell = [self getCellByTitle:title section:section];
    
    if ([cell isKindOfClass:[TSMsgContentItemCell class]]) {
        TSMsgContentItemCell *item_cell = (TSMsgContentItemCell *)cell;
        content = item_cell.contentTextField.text;
    }
    else if ([cell isKindOfClass:[TSMsgDatePickerTextFieldCell class]]){
        TSMsgDatePickerTextFieldCell *date_cell = (TSMsgDatePickerTextFieldCell *)cell;
        NSDateFormatter *format = [[NSDateFormatter alloc] init];
        [format setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        content = [format stringFromDate:date_cell.contentTextField.datePicker
                   .date];
    }
    else if ([cell isKindOfClass:[TSPickerViewTextFieldCell class]]){
        TSPickerViewTextFieldCell *picker_cell = (TSPickerViewTextFieldCell *)cell;
        content = picker_cell.contentTextField.text;
    }
    
    return content;
}

-(void)addNewNode
{
    nodeCount++;
    //遍历数据，保存
    [userArray addObject:@""];
    [self reloadData];
}

@end

